import router from '@/router';
import NProgress from 'nprogress';
import {Message} from 'element-ui';
import {getToken, parseToken} from '@/utils/token';
import {getUserInfo, setUserInfo} from '@/utils/user';

const withList = ['/login'];

function inWithList(path) {
    return withList.includes(path);
}

router.beforeEach(async (to, from, next) => {
    NProgress.start();

    const hasToken = getToken();
    // 无 Token
    if (!hasToken) {
        if (inWithList(to.path)) {
            next();
            return;
        }
        next(`/login?redirect=${to.path}`);
        NProgress.done();
        return;
    }
    // Token
    if (to.path === '/login') {
        next({path: '/'});
        NProgress.done();
        return;
    }
    const hasUserInfo = getUserInfo();
    if (!hasUserInfo) {
        console.log('setUser');
        setUserInfo(parseToken(hasToken));
    } 
    next();
});

router.afterEach(() => {
    NProgress.done();
});
